import {
  BadRequestException,
  Injectable,
  NotFoundException,
} from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Banner } from 'src/core/entities/banner.entity';
import { Cart } from 'src/core/entities/cart.entity';
import { Favorite, FavoriteTypes } from 'src/core/entities/favorite.entity';
import { Order } from 'src/core/entities/order.entity';
import { Product } from 'src/core/entities/product.entity';
import { Quick } from 'src/core/entities/quick.entity';
import { User, UserAddress } from 'src/core/entities/user.entity';
import { Repository } from 'typeorm';

@Injectable()
export class WeappService {
  constructor(
    @InjectRepository(Cart)
    private readonly cartRepository: Repository<Cart>,
    @InjectRepository(Product)
    private readonly productRepository: Repository<Product>,
    @InjectRepository(User)
    private readonly userRepository: Repository<User>,
    @InjectRepository(UserAddress)
    private readonly addressRepository: Repository<UserAddress>,
    @InjectRepository(Order)
    private readonly orderRepository: Repository<Order>,
    @InjectRepository(Banner)
    private readonly bannerRepository: Repository<Banner>,
    @InjectRepository(Quick)
    private readonly quickRepository: Repository<Quick>,
    @InjectRepository(Favorite)
    private readonly favoriteRepository: Repository<Favorite>,
  ) {}

  async addFavorite(userId: number, type: FavoriteTypes, resourceId: number) {
    // 检查资源是否存在（根据类型查询对应表）
    if (!(await this.checkResourceExists(type, resourceId))) {
      throw new Error('资源不存在');
    }

    // 避免重复收藏
    const exists = await this.favoriteRepo.findOne({
      userId,
      type,
      resourceId,
    });
    if (exists) throw new Error('已收藏');

    return this.favoriteRepo.save({ userId, type, resourceId });
  }

  /**
   * 获取轮播
   * @returns 轮播列表
   */
  listBanner() {
    return this.bannerRepository.find();
  }

  /**
   * 获取快捷链接
   * @returns 快捷链接列表
   */
  listQuick() {
    return this.quickRepository.find();
  }

  /**
   * 获取购物车
   * @param userId 用户ID
   * @returns 购物车计算结果及列表
   */
  async listCart(userId: number) {
    const list = await this.cartRepository.find({
      where: {
        userId,
      },
    });

    let total = 0;
    // 1. 需要将选中项目
    list.map((item) => {
      if (item.checked) total += item.price * item.quantity;
    });

    return {
      total,
      list,
    };
  }

  /**
   * 加入购物车
   * @param userId 用户ID
   * @param productId 商品ID
   * @param spec 规格
   * @param quantity 数量
   * @returns 更新结果
   */
  async pushCart(
    userId: number,
    productId: number,
    spec: string,
    quantity: number,
  ) {
    // 1. 检查是否存在相同商品和规格的记录
    const existingItem = await this.cartRepository.findOne({
      where: { userId: userId, productId: productId, spec: spec },
    });
    if (existingItem) {
      // 2. 存在则更新数量
      existingItem.quantity += quantity;
      return this.cartRepository.save(existingItem);
    } else {
      // 3. 不存在则新增
      const newItem = this.cartRepository.create({
        userId,
        productId,
        spec,
        quantity,
      });
      return this.cartRepository.save(newItem);
    }
  }

  async specCart(cartId: number, spec: string, userId: number) {
    const cartItem = await this.cartRepository.findOne({
      where: { id: cartId, userId },
    });

    if (!cartItem) throw new NotFoundException('购物车项不存在');

    // 验证新规格是否合法（需根据商品表spec_options校验）
    const product = await this.productService.findById(cartItem.productId);
    if (!this.validateSpecs(product.spec_options, newSpecs)) {
      throw new BadRequestException('规格不合法');
    }

    cartItem.spec = spec;
    return this.cartRepository.save(cartItem);
  }

  async quantityCart(cartId: number, userId: number, quantity: number) {
    const cartItem = await this.cartRepository.findOne({
      where: { id: cartId, userId },
    });
    if (!cartItem) throw new NotFoundException('无效记录');
    // 库存校验(库存不足,更新失败,库存充足,更新成功)
    return this.cartRepository.save(cartItem);
  }

  async removeCart(cartId: number, userId: number) {
    const cartItem = await this.cartRepository.findOne({
      where: { id: cartId, userId },
    });
    if (!cartItem) throw new NotFoundException('无效记录');
    return this.cartRepository.delete(cartItem.id);
  }
}
